require 'Common/define'
require 'Logic/Config'
require 'Common/functions'
require 'View/PopUI/UIHeroHandbookItem'

UIHeroHandbook = {};
HelperFunc.SetUIEnv(UIHeroHandbook)
local this = UIHeroHandbook;


this.hasInit = false;

---@type FairyGUI.GList

this.tableTab ={};  -- tab页签
---@type UIHeroHandbookItem
this.mainHeroPosInfo = nil; -- 主角英雄信息
---@type UIHeroHandbookItem[]
this.tableHeroPosInfo ={}; -- 英雄列表信息
this.selectType = 0; --当前选中页签

this.currentHeroConfigList = nil;

this.crystalConfig = nil;
this.createCharactorConfig = nil;
this.heroConfig = nil;
this.heroRankConfig = nil;
this.heroMaxLevel =0;
this.heroDataList = {}

---@type FairyGUI.Controller
this.ctrlTab = nil
this.objectName = nil
this.btnTip = nil;
function UIHeroHandbook.Init()--todo 应该小写 暂时先大写
    if crystalConfig == nil then
        crystalConfig =G.dataTable["t_crystal"];
    end
    if createCharactorConfig == nil then
        createCharactorConfig =G.dataTable["t_createCharacter"];
    end
    if heroConfig == nil then
        heroConfig =G.dataTable["t_hero"];
    end
    if heroRankConfig == nil then
        heroRankConfig =G.dataTable["t_herorank"]
    end
    if heroMaxLevel ==0 then
        local heroExpConfig = G.dataTable["t_characterexp"];
        for key, value in pairs(heroExpConfig) do
            if value.f_CharacterLevel > heroMaxLevel then
                heroMaxLevel =  value.f_CharacterLevel;
            end
        end
    end

    selectType = EnumConst.HeroTypeEnum.HeroType1

    local name,package = getUIName(PanelResNames.UIHeroHandbook);
    panelMgr:ShowUI(name,package ,this.onCreate, Config.useLocalUI);
end

---@param obj GComponent
function UIHeroHandbook.onCreate(obj)
    AddUIPackageDepend(PanelResNames.UIHeroHandbook,"FUI/HalfBodyAtlas")
    if not hasInit then
        hasInit = true;
        objectName = obj.gameObjectName
        btnTip = obj:GetChild("tips");
        this.bind = {
            btnReward = obj:GetChild("RewardBtn"),
            txtNum = obj:GetChild("NumText"),
            txtStage = obj:GetChild("StageText"),
            btnBack = obj:GetChild("BackBtn"),
            ---@type FairyGUI.GList
            listHero = obj:GetChild("Sv"),
            ctrlTab = obj:GetController("ctrlTab"),
            ctrlRewardActive = obj:GetController("ctrlRewardActive"),
            progress = obj:GetChild("progress")
            --objHero = obj:GetChild("hero"),
        }
        this.itemPoolMgr = ComponentPoolMgr.New(UIHeroHandbookItem)
        this.addEvent();
        UIRedDots.addViewListen(PanelResNames.UIHeroHandbook,objectName..this.bind.btnReward.name,this.bind.btnReward,Config.RedDotsType.HeroCrystal);
        this.bind.listHero.itemRenderer = this.ListItemRenderer
    end

    this.bind.ctrlTab.selectedIndex = 1
    this.refresh();
end

function UIHeroHandbook.addEvent()
    this.bind.btnReward.onClick:Add(this.onClickReward)
    this.bind.btnBack.onClick:Add(this.onClickBack)
    this.bind.ctrlTab.onChanged:Add(this.OnTabChanged)
    btnTip.onClick:Add(this.ShowTips)
end

function UIHeroHandbook.removeEvent()
    this.bind.btnReward.onClick:Clear()
    this.bind.btnReward.onClick:Clear()
    this.bind.ctrlTab.onChanged:Clear()
    btnTip.onClick:Clear();
end

function UIHeroHandbook.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_Handbook,this.resetData);
    ListenEvent(Config.EventType.Fresh_Crystal,this.resetData);
    ListenEvent(Config.EventType.Fresh_Mercenary,this.resetData);
end

function UIHeroHandbook.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_Handbook,this.resetData);
    CloseEvent(Config.EventType.Fresh_Crystal,this.resetData);
    CloseEvent(Config.EventType.Fresh_Mercenary,this.resetData);
end

function UIHeroHandbook.OnDestroy()
    this.removeEvent();
    if this.itemPoolMgr then
        this.itemPoolMgr:OnDestroy()
        this.itemPoolMgr = nil
    end

    UIRedDots.removeViewEvent(PanelResNames.UIHeroHandbook)

    if UIPackage.GetById("FUI/HalfBodyAtlas") then
        UIPackage.RemovePackage("FUI/HalfBodyAtlas")
    end
end

function UIHeroHandbook.OnEnable()
    this.LocalListenEvent();
end

function UIHeroHandbook.OnDisable()
    this.LocalCloseEvent();
end

function UIHeroHandbook.ShowTips()
    local txts = {};
    txts["title"] = "HelpTitle5";
    txts["des"] = "HelpDes5";
    showUI(PanelNames.CommonTips,txts);
end

function UIHeroHandbook.resetData() --回调重刷
    this.refresh();
end


function UIHeroHandbook.refresh()
    --刷新函数
    local level = logicMgr.HeroManager.getCrystalInfo().level;
    local exp = logicMgr.HeroManager.getCrystalInfo().exp;

    local cg = crystalConfig[tostring(level)];
    if cg~=nil then
        this.bind.txtStage.text = getLanguage(cg.f_Name);
        if exp > cg.f_Value then
            exp = cg.f_Value;
        end
        this.bind.txtNum.text = exp.."/"..cg.f_Value;
        this.bind.progress.value = exp*100 / cg.f_Value;
        if exp >= cg.f_Value then
            this.bind.ctrlRewardActive.selectedIndex = 1
        else
            this.bind.ctrlRewardActive.selectedIndex = 0
        end
    else
        cg = crystalConfig[tostring(level-1)];
        this.bind.txtStage.text = getLanguage(cg.f_Name);
        this.bind.progress.value = 100;
        this.bind.txtNum.text = getLanguage("PetApply_MaxLevel");
    end

    this.refreshPage();
end

function UIHeroHandbook.refreshPage(index)
    local index = this.bind.ctrlTab.selectedIndex
    table.clear(heroDataList)
    local mainHero = nil;
    for key, value in pairs(heroConfig) do
        if value.f_Type ~= 2 and value.f_Type ~= 3 then
            if value.f_HeroType == index then
                --if mainHero == nil and createCharactorConfig[key]~=nil then
                --    mainHero = value;
                --else
                table.insert(heroDataList,value);
                --end
            end
        end
    end

    table.sort(heroDataList,function (a,b)
        if a.f_HeroInitialStar~= b.f_HeroInitialStar then
            return a.f_HeroInitialStar>b.f_HeroInitialStar;
        end
        return a.f_HeroID< b.f_HeroID;
    end);
    currentHeroConfigList= {};
    if  mainHero~=nil then
        local heroData = {};
        logicMgr.HeroManager.copyHeroConfig(mainHero,heroData);
        table.insert(currentHeroConfigList,heroData);
    end

    for i = 1, #heroDataList do
        local heroData = {};
        logicMgr.HeroManager.copyHeroConfig(heroDataList[i],heroData);
        table.insert(currentHeroConfigList,heroData);
    end
    this.bind.listHero.numItems = #heroDataList
end

function UIHeroHandbook.ListItemRenderer(index,go)
    index = index + 1
    local data = heroDataList[index]
    ---@type UIHeroHandbookItem
    local item = this.itemPoolMgr:GetBindScript(go)
    item:Refresh(data,index,this.OnClickHero)
end



function UIHeroHandbook.onClickReward()
    local level = logicMgr.HeroManager.getCrystalInfo().level;
    local exp = logicMgr.HeroManager.getCrystalInfo().exp;

    local cg = crystalConfig[tostring(level)];

    if cg==nil then
        return;
    end

    if exp >= cg.f_Value then
        drawHandler.sendCrystal();
    else
        showUI(PanelNames.UIHeroHandbookReward);
    end
end

function UIHeroHandbook.OnClickHero(modelId)
    local maxStar = logicMgr.HeroManager.LimitStar()
    for i = 1, #currentHeroConfigList do
        local hero = currentHeroConfigList[i];
        hero.level = heroMaxLevel;
        local config = heroRankConfig[tostring(hero.partnerModelId*10+hero.star)];
        while config~=nil and config.f_HeroStarNext~=nil and config.f_HeroStarNext>0 do
            config = heroRankConfig[tostring(config.f_HeroStarNext)];
        end
        if config~=nil then
            hero.star = config.f_HeroStar;
        end
        logicMgr.HeroManager.processHeroBaseAttr(hero,hero.level,hero.star);
        logicMgr.HeroManager.processHeroAllAttr(hero);
    end

    showUI(PanelNames.UICharactorPreview,currentHeroConfigList,modelId);
end

function UIHeroHandbook.onClickBack()
    closeUI(PanelNames.UIHeroHandbook);
end
function UIHeroHandbook.OnTabChanged()

    this.refreshPage();
end

return UIHeroHandbook;
